﻿using System;
using System.Diagnostics;
using System.IO;

namespace Com.Lancetinc.Evs.Helpers
{
    public static class TempDirHelper
    {
        public static string GetImageTempDir()
        {
            string path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            return Path.Combine(path, "images");
        }

        public static string GetTempImageFilePath(string rawImageFilePath)
        {
            string md5 = Md5Utils.Encrypt(rawImageFilePath) + "." + Path.GetExtension(rawImageFilePath);
            string tempPath = Path.Combine(GetImageTempDir(), md5);
            if (File.Exists(tempPath))
            {
                return tempPath;
            }
            Directory.CreateDirectory(Path.GetDirectoryName(tempPath));
            File.Copy(rawImageFilePath, tempPath);
            return tempPath;
        }

        public static void DeleteTempImageFiles()
        {
            var tempDir = GetImageTempDir();
            if (!Directory.Exists(tempDir))
            {
                return;
            }
            string[] filePaths = Directory.GetFiles(GetImageTempDir());
            foreach (string filePath in filePaths)
            {
                try
                {
                    File.Delete(filePath);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            }
        }

        /// <summary>
        /// 创建临时文件夹
        /// </summary>
        /// <returns></returns>
        public static string GetTempDirectory()
        {
            var fileName = Path.GetRandomFileName().Replace(".", "_");
            var tempDirectory = Path.Combine(Path.GetTempPath(), fileName);
            Directory.CreateDirectory(tempDirectory);
            return tempDirectory;
        }
    }
}
